package com.yosaa.back.controller;

import com.alibaba.fastjson2.JSON;
import com.yosaa.back.entity.vo.KafkaData;
import com.yosaa.back.service.IScoringStandardService;
import com.yosaa.back.utils.ApiResponse;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/kafka")
public class KafkaController {
    @Resource
    private KafkaTemplate kafkaTemplate;
    @Resource
    private IScoringStandardService scoringStandardService;

    @KafkaListener(topics = "data", groupId = "1")
    public void listenReportTaskFromKafka(@Payload String taskStr, Acknowledgment ack) {
        KafkaData task = JSON.parseObject(taskStr, KafkaData.class);
        scoringStandardService.processDataFromKafka(task, ack);
    }

    @PostMapping("/add")
    public ResponseEntity addDataToKafka(@RequestBody KafkaData dto) {

        try {
            kafkaTemplate.send("data", JSON.toJSONString(dto)).get();
            return ResponseEntity.ok(new ApiResponse(0, null, "操作成功"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResponseEntity.ok(new ApiResponse(1, null,"操作失败"));
        }
    }


}
